/*
用来指定商品详情的富文本编辑器组件
 */
import React from 'react'
import PropTypes from 'prop-types'
import { Editor } from 'react-draft-wysiwyg';
import { EditorState,  ContentState,convertToRaw } from 'draft-js'
import htmlToDraft from 'html-to-draftjs'
import draftToHtml from 'draftjs-to-html'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'

export default class RichTextEditor extends React.Component {
    static propTypes={
        detail:PropTypes.string
    }
    state={
        editorState:EditorState.createEmpty()  //创建一个没有内容的编辑对象
    }
    constructor(props){
        super(props)
        const html = this.props.detail
        if (html) {// 如果有值, 根据html格式字符串创建一个对应的编辑对象
            const contentBlock = htmlToDraft(html);
            const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
            const editorState = EditorState.createWithContent(contentState);
            this.state = {
                editorState,
            }
        }else{
            this.state={
                editorState:EditorState.createEmpty()  //创建一个没有内容的编辑对象
            }
        }

    }
    /*
    输入过程中的实时回调
    */

    onEditorStateChange=(editorState) => {
        this.setState({
          editorState,
        })
    }
    getDetail=()=>{
          // 返回输入数据对应的html格式的文本
        return draftToHtml(convertToRaw(this.state.editorState.getCurrentContent()))
    }
      // 富文本编辑器上传图片后的回调函数
   
    uploadImageCallBack=(file)=>{
    return new Promise(
      (resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open('POST', 'http://120.55.193.14:5000/manage/img/upload')
        xhr.setRequestHeader('Authorization', 'Client-ID XXXXX')
        const data = new FormData()
        data.append('image', file)
        xhr.send(data)
        xhr.addEventListener('load', () => {
          const response = JSON.parse(xhr.responseText)
          const urlArray = response.data.url.split("/")
          const newUrl = `http://120.55.193.14:5000/upload/${urlArray[urlArray.length-1]}`
          console.log(newUrl)
          resolve({ data: { link: newUrl } })
        })
        xhr.addEventListener('error', () => {
          const error = JSON.parse(xhr.responseText)
          reject(error)
        });
      }
    );
  }
  
    render() {
        return (
            <Editor 
             editorState={this.state.editorState}
             onEditorStateChange={this.onEditorStateChange} 
             toolbar={{ image: { uploadCallback: this.uploadImageCallBack, alt: { present: true, mandatory: true }},}}
             editorStyle={{border:'1px solid black',minHeight:200,paddingLeft:10}}/> 
            )
    }
}
